<?php
require_once dirname(__FILE__) . '/User/Item.php';

class Storefront_Resource_User 
    extends SF_Model_Resource_Db_Table_Abstract
    implements Storefront_Resource_User_Interface
{
    
    protected $_name = 'user';
    protected $_primary = 'userId';
    protected $_rowClass = 'Storefront_Resource_User_Item';
    
    /**
     *
     * @param string $email
     * @param type $ignoreUser
     * @return Storefront_Resource_User_Item | null
     */
    public function getUserByEmail($email, $ignoreUser = NULL) 
    {
        
        $select = $this->select();
        $select->where('email = ?', $email);
        
        if(NULL !== $ignoreUser) {
            $select->where('email != ?', $ignoreUser->email);
        }
        
        return $this->fetchRow($select);
        
    }

    /**
     * Get user by id
     *
     * @param int $id
     * @return Storefront_Resource_User_Item | null
     */
    public function getUserById($id) 
    {
        
        return $this->find($id)->current();
        
    }

    /**
     * Get all  users
     *
     * @param boolean $paged
     * @param string $order
     * @return Zend_Db_Table_Rowset | Zend_Paginator
     */
    public function getUsers($paged = FALSE, $order = NULL) 
    {
        //$select = $this->select();
        
        if(true === is_array($order)) {
            // strano $select non è instanziato !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            $select->order($order);
        }
        
        if(NULL !== $paged) {
            $adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
            $count = clone $select;
            $count->reset(Zend_Db_Select::COLUMNS);
            $count->reset(Zend_Db_Select::FROM);
            $count->from('user', new Zend_Db_Expr('COUNT(*) AS `zend_paginator_row_count`'));
            $adapter->setRowCount($count);
            
            $paginator = new Zend_Paginator($adapter);
            $paginator->setItemCountPerPage(15)
                      ->setCurrentPageNumber((int) $paged);
            
            return $paginator;
        }
        
        return $this->fetchAll($select);
    }

    
}